<template>
  <view class="app-container">
    <!-- 返回上一页 -->
    <u-navbar :title="isEditMode ? '编辑产品' : '新建产品'" autoBack leftIcon="arrow-left" fixed safeAreaInsetTop />
    <!-- 页面内容 -->
    <scroll-view scroll-y class="content">
      <!-- 经营协议 -->
      <view class="card">
        <view class="card-header">经营协议</view>
        <view class="card-body">
          <view class="agreement-links">
            <view class="agreement-link-item">
              <text @click="showAgreement('参营协议')" class="agreement-link">《参营协议》</text>
              <text class="agreement-tip">、</text>
            </view>
            <view class="agreement-link-item">
              <text @click="showAgreement('接团协议')" class="agreement-link">《接团协议》</text>
              <text class="agreement-tip">和</text>
            </view>
            <view class="agreement-link-item">
              <text @click="showAgreement('随队协议')" class="agreement-link">《随队协议》</text>
              <text class="agreement-tip">。</text>
            </view>
          </view>
          <!-- 已阅读协议单选框 -->
          <view class="agreement-read">
            <up-checkbox :customStyle="{ marginBottom: '8px' }" label="我已阅读并同意以上协议" name="agree" usedAlone
              v-model:checked="hasReadAgreement" @change="handleReadChange">
            </up-checkbox>
          </view>
        </view>
      </view>

      <!-- 首图 / 轮播图上传 -->
      <view class="card">
        <view class="card-header">首图 / 轮播图</view>
        <view class="card-body">
          <view class="image-upload">
            <view v-for="(img, index) in form.images" :key="index" class="image-item">
              <image :src="img.url" mode="aspectFill" />
              <view class="delete" @click="confirmRemove(index)">×</view>
            </view>
            <view v-if="form.images.length < 8" class="upload-btn" @click="chooseImage">
              +
            </view>
          </view>
          <text class="tips">最多上传 8 张图片</text>
        </view>
      </view>

      <!-- 研学旅行类别标签 -->
      <view class="card">
        <view class="card-header">研学旅行类别</view>
        <view class="card-body">
          <!-- 一级和二级分类选择在同一行 -->
          <view class="category-container">
            <!-- 一级分类选择 -->
            <view class="category-item">
              <picker mode="selector" :range="categoryOptions.map(cat => cat.text)" @change="onMainCategoryChange">
                <view class="picker-value">
                  {{ selectedMainCategory || "请选择一级类别" }}
                </view>
              </picker>
            </view>

            <!-- 二级分类选择 - 即使一级分类未选择也显示 -->
            <view v-if="currentSubCategories.length > 0" class="category-item">
              <picker mode="selector" :range="currentSubCategories.map(sub => sub.text)" @change="onSubCategoryChange">
                <view class="picker-value">
                  {{ selectedSubCategory || "请选择二级类别" }}
                </view>
              </picker>
            </view>
          </view>
        </view>
      </view>

      <!-- 产品标题 -->
      <view class="card">
        <view class="card-header">产品标题</view>
        <view class="card-body">
          <input class="input" maxlength="100" placeholder="请输入产品标题（必填，最多100字）" v-model="form.name" />
          <view class="input-count">{{ form.name.length }}/100</view>
        </view>
      </view>

      <!-- 产品特色（可展开卡片） -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('feature')">
          产品特色
          <text class="arrow">{{ expanded.feature ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.feature">
          <view class="section-content" v-if="productStore.subPageData?.productFeatures.length > 0">
            <view v-for="(item, index) in productStore.subPageData.productFeatures" :key="index">
              <!-- 图片类型 -->
              <view v-if="item.imgUrl" style="margin-bottom: 16rpx;">
                <image :src="item.imgUrl" mode="widthFix" style="width: 100%; min-height: 200rpx; object-fit: contain;"
                  @error="onImageError($event, index)" @load="onImageLoad" />
                <!-- 图片加载失败时显示的占位符 -->
                <view v-if="imageErrors[index]" class="image-error-placeholder">
                  <text>图片加载失败</text>
                </view>
              </view>
              <!-- 文本类型 -->
              <view v-if="item.alt" style="margin-bottom: 16rpx;">
                <text>{{ item.alt }}</text>
              </view>
            </view>
          </view>
          <view class="section-content"
            v-else-if="productStore && productStore.subPageData && productStore.subPageData.feature">
            <!-- 优化显示，避免直接显示JSON字符串 -->
            {{ featurePreview }}
          </view>
          <!-- 确保数据同步：当没有产品特色数据时，强制清空视图 -->
          <view
            v-else-if="productStore && productStore.subPageData && (!productStore.subPageData.productFeatures || productStore.subPageData.productFeatures.length === 0)"
            style="text-align: center; color: #999; padding: 20rpx;">
            暂无产品特色内容
          </view>
          <view class="section-content" v-else>暂无产品特色内容。</view>
          <button size="mini" class="inner-edit-btn" @click.stop="goToFeature">去编辑</button>
        </view>
      </view>

      <!-- 具体行程（可展开卡片） -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('itinerary')">
          具体行程
          <text class="arrow">{{ expanded.itinerary ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.itinerary">
          <!-- 新的数据结构：按天数分组 -->
          <view class="section-content" v-if="productStore.subPageData?.specificItinerary.length > 0">
            <!-- 按天显示行程 -->
            <view v-for="(dayItinerary, dayIndex) in productStore.subPageData.specificItinerary" :key="dayItinerary.day"
              class="itinerary-day-summary">
              <view class="day-title">第{{ dayItinerary.day }}天：{{ dayItinerary.main || '行程' }}</view>
              <view v-if="dayItinerary.items && dayItinerary.items.length > 0" class="day-items">
                <view v-for="(item, itemIndex) in dayItinerary.items" :key="itemIndex" class="itinerary-item">
                  <view class="item-title">
                    <span class="item-type">{{ item.alt }}</span>
                    <span class="item-name">{{ item.title }}</span>
                  </view>
                  <view class="item-details">
                    <text class="item-time">{{ item.startTime }} - {{ item.endTime }}</text>
                    <text v-if="item.address" class="item-address">{{ item.address }}</text>
                  </view>
                </view>
              </view>
              <view v-else class="empty-items">暂无行程项目</view>
            </view>
          </view>
          <!-- 使用行程摘要计算属性 -->
          <view class="section-content"
            v-if="productStore && productStore.subPageData && productStore.subPageData.specificItinerary && productStore.subPageData.specificItinerary.length > 0">
            <!-- 按天显示行程摘要 -->
            <view v-for="(dayItem, dayIndex) in itinerarySummary" :key="dayIndex" class="itinerary-day-summary">
              <view class="day-title">第{{ dayIndex + 1 }}天：{{ dayItem.title || '行程' }}</view>
              <view v-if="dayItem.items && dayItem.items.length > 0" class="day-items-summary">
                <text class="items-count">共{{ dayItem.items.length }}个行程项目</text>
                <text v-if="dayItem.firstItem" class="first-item">· {{ dayItem.firstItem }}</text>
              </view>
            </view>
          </view>
          <!-- 确保数据同步：当没有具体行程数据时，强制清空视图 -->
          <view
            v-else-if="productStore && productStore.subPageData && (!productStore.subPageData.specificItinerary || productStore.subPageData.specificItinerary.length === 0)"
            style="text-align: center; color: #999; padding: 20rpx;">
            暂无具体行程的内容或摘要
          </view>
          <view class="section-content" v-else>暂无具体行程的内容或摘要。</view>
          <button size="mini" class="inner-edit-btn" @click.stop="goToItinerary">去编辑</button>
        </view>
      </view>

      <!-- 费用包含（可展开卡片） -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('included')">
          费用包含
          <text class="arrow">{{ expanded.included ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.included">
          <view class="section-content" v-if="productStore.subPageData?.expensesIncluded.length > 0">
            <view v-for="(item, index) in productStore.subPageData?.expensesIncluded" :key="index" class="expense-item">
              <view class="expense-title">{{ item.title }}</view>
              <view class="expense-content">{{ item.alt }}</view>
            </view>
          </view>
          <!-- 确保数据同步：当没有费用包含数据时，强制清空视图 -->
          <view v-else-if="productStore.subPageData?.expensesIncluded.length === 0"
            style="text-align: center; color: #999; padding: 20rpx;">
            暂无费用包含的内容或摘要
          </view>
          <view class="section-content" v-else>暂无费用包含的内容或摘要。</view>
          <button size="mini" class="inner-edit-btn" @click.stop="goToExpenses('included')">去编辑</button>
        </view>
      </view>

      <!-- 费用不含（可展开卡片） -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('excluded')">
          费用不含
          <text class="arrow">{{ expanded.excluded ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.excluded">
          <view class="section-content" v-if="productStore.subPageData?.expensesExcluded.length > 0">
            <view v-for="(item, index) in productStore.subPageData?.expensesExcluded" :key="index" class="expense-item">
              <view class="expense-title">{{ item.title }}</view>
              <view class="expense-content">{{ item.alt }}</view>
            </view>
          </view>
          <!-- 确保数据同步：当没有费用不含数据时，强制清空视图 -->
          <view v-else-if="productStore.subPageData?.expensesExcluded.length === 0"
            style="text-align: center; color: #999; padding: 20rpx;">
            暂无费用不含的内容或摘要
          </view>
          <view class="section-content" v-else>暂无费用不含的内容或摘要。</view>
          <button size="mini" class="inner-edit-btn" @click.stop="goToExpenses('excluded')">去编辑</button>
        </view>
      </view>

      <!-- 另付费项目（可展开卡片） -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('other')">
          另付费项目
          <text class="arrow">{{ expanded.other ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.other">
          <view class="section-content" v-if="productStore.subPageData?.otherExpenses.length > 0">
            <view v-for="(item, index) in productStore.subPageData?.otherExpenses" :key="index" class="expense-item">
              <view class="expense-content">{{ item.alt }}</view>
            </view>
          </view>
          <!-- 确保数据同步：当没有另付费项目数据时，强制清空视图 -->
          <view
            v-else-if="productStore && productStore.subPageData && (!productStore.subPageData.otherExpenses || productStore.subPageData.otherExpenses.length === 0)"
            style="text-align: center; color: #999; padding: 20rpx;">
            暂无另付费项目的内容或摘要
          </view>
          <view v-else class="section-content">暂无另付费项目的内容或摘要。</view>
          <button size="mini" class="inner-edit-btn" @click.stop="goToExpenses('other')">去编辑</button>
        </view>
      </view>

      <!-- 风险提示（可展开卡片） -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('riskPrompt')">
          风险提示
          <text class="arrow">{{ expanded.riskPrompt ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.riskPrompt">
          <view class="section-content"
            v-if="productStore.subPageData && productStore.subPageData.riskPrompt && productStore.subPageData.riskPrompt.trim() !== ''">
            {{ productStore.subPageData.riskPrompt }}
          </view>
          <!-- 确保数据同步：当没有风险提示数据时，强制清空视图 -->
          <view
            v-else-if="productStore.subPageData && productStore.subPageData.riskPrompt && productStore.subPageData.riskPrompt.trim() === ''"
            style="text-align: center; color: #999; padding: 20rpx;">
            暂无风险提示的内容或摘要
          </view>
          <view v-else class="section-content" style="text-align: center; color: #999; padding: 20rpx;">暂无风险提示的内容或摘要
          </view>
          <button size="mini" class="inner-edit-btn" @click.stop="goToExpenses('risk')">去编辑</button>
        </view>
      </view>


      <!-- 保障提示（可展开卡片） -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('guaranteePrompt')">
          保障提示
          <text class="arrow">{{ expanded.guaranteePrompt ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.guaranteePrompt">
          <view class="section-content"
            v-if="productStore.subPageData && productStore.subPageData.guaranteePrompt && productStore.subPageData.guaranteePrompt.trim() !== ''">
            {{ productStore.subPageData.guaranteePrompt }}
          </view>
          <!-- 确保数据同步：当没有保障提示数据时，强制清空视图 -->
          <view
            v-else-if="productStore.subPageData && productStore.subPageData.guaranteePrompt && productStore.subPageData.guaranteePrompt.trim() === ''"
            style="text-align: center; color: #999; padding: 20rpx;"> 暂无保障提示的内容或摘要
          </view>
          <view class="section-content" style="text-align: center; color: #999; padding: 20rpx;" v-else>暂无保障提示的内容或摘要
          </view>
          <button size="mini" class="inner-edit-btn" @click.stop="goToExpenses('guarantee')">去编辑</button>
        </view>
      </view>

      <!-- 预定须知 -->
      <view class="card">
        <view class="card-header expandable" @click="toggleSection('bookingInfo')">
          预定须知
          <text class="arrow">{{ expanded.bookingInfo ? '▲' : '▼' }}</text>
        </view>
        <view class="card-body" v-if="expanded.bookingInfo">
          <view class="form-item">
            <text>参营年龄范围</text>
            <view class="age-range-slider">
              <up-slider :rangeValue="ageRange" :min="3" :max="18" :step="1" isRange :show-value="true"></up-slider>
              <text class="tips">参营年龄范围: {{ ageRange[0] }} - {{ ageRange[1] }} 岁</text>
            </view>
          </view>

          <view class="form-item">
            <text>家长陪同</text>
            <switch :checked="form.parentsAccompanied" @change="form.parentsAccompanied = $event.detail.value" />
            <text class="tips">
              {{ form.parentsAccompanied ? "需要陪同" : "无需陪同" }}
            </text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="bottom-btns">
      <button class="btn preview" :disabled="isSaving || isUploading" @click="onPreview">预览</button>
      <button v-if="!isEditMode" class="btn next"
        :disabled="!isFormValid || !hasReadAgreement || isSaving || isUploading" @click="onNext">提交</button>
      <button v-if="isEditMode" class=" btn next"
        :disabled="!isFormValid || !hasReadAgreement || isSaving || isUploading" @click="onUpdate">保存</button>
    </view>

    <!-- 协议弹窗组件 -->
    <u-popup ref="agreementPopup" mode="bottom" :show="showPopup" @close="onPopupClose" :mask-close-able="false">
      <view class="popup-container">
        <view class="popup-header">
          <text class="popup-title">{{ popupTitle }}</text>
          <u-icon name="close" size="28" @click="closeAgreementPopup"></u-icon>
        </view>
        <scroll-view class="popup-content" scroll-y>
          <view v-if="currentAgreement === '参营协议'" class="agreement-content">
            <text class="agreement-title">参营协议</text>
            <text class="agreement-date">更新日期：2025年09月03日 生效日期：2025年09月03日</text>
            <text class="agreement-paragraph">一、 协议目的
              本参营协议（以下简称"协议"）由参营方（以下简称"参营方"）与得炼（郑州）信息科技有限公司（以下简称"平台方"）共同签署，旨在规范参营方在纤程旅行平台上开展研学旅行相关活动的行为，保障平台方、参营方及用户的权益利。</text>
            <text class="agreement-paragraph">二、 参营方资质与义务
              2.1 参营方应具备开展研学旅行活动的合法资质，包括但不限于LICENSE、相关许可证等，并确保所提供的所有资质文件真实、有效。
              2.2 参营方应遵守国家相关法律法规，严格按照研学旅行活动的相关标准和要求组织开展活动，确保活动的安全性和教育性。</text>
            <text class="agreement-paragraph">三、 平台方权利与义务
              3.1 平台方有权对参营方的资质、活动内容、服务质量等进行审核和监督。
              3.2 平台方应向参营方提供必要的技术支持和服务，协助参营方开展研学旅行活动。</text>
            <text class="agreement-paragraph">四、 费用与结算
              4.1 参营方应按照平台方的规定支付相关费用，包括但不限于平台服务费、推广费等。
              4.2 平台方应按照双方约定的时间和方式与参营方进行结算。</text>
            <text class="agreement-paragraph">五、 协议变更与终止
              5.1 本协议的变更或补充应经双方协商一致，并以书面形式确认。
              5.2 如参营方违反本协议的约定，平台方有权单方面终止本协议，并追究参营方的违约责任。</text>
            <text class="agreement-paragraph">六、 争议解决
              6.1 本协议的订立、效力、解释、履行和争议的解决，均适用中华人民共和国大陆地区法律。
              6.2 因本协议引起的任何争议，双方应首先友好协商解决；协商不成的，任何一方均有权将争议提交至平台所在地（河南省郑州市）有管辖权的人民法院诉讼解决。</text>
          </view>
          <view v-else-if="currentAgreement === '接团协议'" class="agreement-content">
            <text class="agreement-title">接团协议</text>
            <text class="agreement-date">更新日期：2025年09月03日 生效日期：2025年09月03日</text>
            <text class="agreement-paragraph">一、 协议目的
              本接团协议（以下简称"协议"）由接团方（以下简称"接团方"）与得炼（郑州）信息科技有限公司（以下简称"平台方"）共同签署，旨在规范接团方在纤程旅行平台上接收研学旅行团队的行为，保障平台方、接团方及用户的权益利。</text>
            <text class="agreement-paragraph">二、 接团方资质与义务
              2.1 接团方应具备接收研学旅行团队的合法资质，包括但不限于旅行社业务经营许可证、相关专业人员资质等，并确保所提供的所有资质文件真实、有效。
              2.2 接团方应按照平台方的要求和标准，为研学旅行团队提供优质的接待服务，包括但不限于交通、住宿、餐饮、导游等服务。</text>
            <text class="agreement-paragraph">三、 平台方权利与义务
              3.1 平台方有权对接团方的资质、服务质量等进行审核和监督。
              3.2 平台方应向接团方提供必要的技术支持和服务，协助接团方开展接团业务。</text>
            <text class="agreement-paragraph">四、 费用与结算
              4.1 接团方应按照平台方的规定收取相关费用，并向平台方支付一定比例的服务费。
              4.2 平台方应按照双方约定的时间和方式与接团方进行结算。</text>
            <text class="agreement-paragraph">五、 协议变更与终止
              5.1 本协议的变更或补充应经双方协商一致，并以书面形式确认。
              5.2 如接团方违反本协议的约定，平台方有权单方面终止本协议，并追究接团方的违约责任。</text>
            <text class="agreement-paragraph">六、 争议解决
              6.1 本协议的订立、效力、解释、履行和争议的解决，均适用中华人民共和国大陆地区法律。
              6.2 因本协议引起的任何争议，双方应首先友好协商解决；协商不成的，任何一方均有权将争议提交至平台所在地（河南省郑州市）有管辖权的人民法院诉讼解决。</text>
          </view>
          <view v-else-if="currentAgreement === '随队协议'" class="agreement-content">
            <text class="agreement-title">随队协议</text>
            <text class="agreement-date">更新日期：2025年09月03日 生效日期：2025年09月03日</text>
            <text class="agreement-paragraph">一、 协议目的
              本随队协议（以下简称"协议"）由随队方（以下简称"随队方"）与得炼（郑州）信息科技有限公司（以下简称"平台方"）共同签署，旨在规范随队方在纤程旅行平台上提供随队服务的行为，保障平台方、随队方及用户的权益利。</text>
            <text class="agreement-paragraph">二、 随队方资质与义务
              2.1 随队方应具备提供随队服务的合法资质和专业能力，包括但不限于相关专业证书、急救证书等，并确保所提供的所有资质文件真实、有效。
              2.2 随队方应按照平台方的要求和标准，为研学旅行团队提供优质的随队服务，包括但不限于安全保障、教育指导、生活照料等服务。</text>
            <text class="agreement-paragraph">三、 平台方权利与义务
              3.1 平台方有权对随队方的资质、服务质量等进行审核和监督。
              3.2 平台方应向随队方提供必要的技术支持和服务，协助随队方开展随队业务。</text>
            <text class="agreement-paragraph">四、 费用与结算
              4.1 随队方应按照平台方的规定收取相关费用，并向平台方支付一定比例的服务费。
              4.2 平台方应按照双方约定的时间和方式与随队方进行结算。</text>
            <text class="agreement-paragraph">五、 协议变更与终止
              5.1 本协议的变更或补充应经双方协商一致，并以书面形式确认。
              5.2 如随队方违反本协议的约定，平台方有权单方面终止本协议，并追究随队方的违约责任。</text>
            <text class="agreement-paragraph">六、 争议解决
              6.1 本协议的订立、效力、解释、履行和争议的解决，均适用中华人民共和国大陆地区法律。
              6.2 因本协议引起的任何争议，双方应首先友好协商解决；协商不成的，任何一方均有权将争议提交至平台所在地（河南省郑州市）有管辖权的人民法院诉讼解决。</text>
          </view>
        </scroll-view>
        <view class="popup-footer">
          <button class="popup-btn" type="primary" @click="closeAgreementPopup">我知道了</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import GlobalTopNav from '@/components/GlobalTopNav.vue';
import { request, BASE_URL } from '@/utils/request.js';
import { useProductStore } from '@/store/product.js';

export default {
  components: {
    GlobalTopNav
  },
  data() {
    return {
      storeIsFormValid: true,
      // 弹窗相关状态
      showPopup: false,
      companyInfo: {},
      popupTitle: '',
      currentAgreement: '',
      categoryOptions: [
        {
          id: 1,
          active: 0,
          text: "亲近自然",
          child: [
            { id: 1001, text: "森林探秘", active: 0 },
            { id: 1002, text: "农耕体验", active: 0 },
            { id: 1003, text: "捕捞采摘", active: 0 },
            { id: 1004, text: "营地生活", active: 0 },
            { id: 1005, text: "观鸟研学", active: 0 },
            { id: 1006, text: "星空观测", active: 0 },
            { id: 1007, text: "昆虫观察", active: 0 },
            { id: 1008, text: "湿地探索", active: 0 },
            { id: 1009, text: "溯溪探险", active: 0 },
            { id: 1010, text: "美景写生", active: 0 },
            { id: 1011, text: "露营体验", active: 0 },
            { id: 1012, text: "植物科考", active: 0 },
            { id: 1013, text: "自然科普", active: 0 }
          ]
        },
        {
          id: 2,
          active: 0,
          text: "户外活动",
          child: [
            { id: 2001, text: "徒步", active: 0 },
            { id: 2002, text: "骑行", active: 0 },
            { id: 2003, text: "攀岩", active: 0 },
            { id: 2004, text: "漂流", active: 0 },
            { id: 2005, text: "滑雪", active: 0 },
            { id: 2006, text: "皮划艇/桨板", active: 0 },
            { id: 2007, text: "速降", active: 0 },
            { id: 2008, text: "励志拓展", active: 0 },
            { id: 2009, text: "野外技能", active: 0 },
            { id: 2010, text: "生存训练", active: 0 },
            { id: 2011, text: "障碍赛", active: 0 }
          ]
        },
        {
          id: 3,
          active: 0,
          text: "科学探索",
          child: [
            { id: 3001, text: "航空相关", active: 0 },
            { id: 3002, text: "人工智能", active: 0 },
            { id: 3003, text: "名校探访", active: 0 },
            { id: 3004, text: "天文科学", active: 0 },
            { id: 3005, text: "职业启蒙", active: 0 },
            { id: 3006, text: "地质考察", active: 0 },
            { id: 3007, text: "工厂/名企探访", active: 0 }
          ]
        },
        {
          id: 4,
          active: 0,
          text: "文化传承",
          child: [
            { id: 4001, text: "劳动实践", active: 0 },
            { id: 4002, text: "红色研学", active: 0 },
            { id: 4003, text: "非遗传承", active: 0 },
            { id: 4004, text: "民俗文化", active: 0 }
          ]
        },
        {
          id: 5,
          active: 0,
          text: "博物历史",
          child: [
            { id: 5001, text: "生物化石", active: 0 },
            { id: 5002, text: "考古模拟", active: 0 },
            { id: 5003, text: "自然博物", active: 0 },
            { id: 5004, text: "遗址探秘", active: 0 }
          ]
        },
        {
          id: 6,
          active: 0,
          text: "国际视野",
          child: [
            { id: 6001, text: "全真插班", active: 0 },
            { id: 6002, text: "名校参访", active: 0 },
            { id: 6003, text: "国际体验", active: 0 },
            { id: 6004, text: "全球生态", active: 0 }
          ]
        }
      ],
      productStore: {},
      expenses: '',
      //编辑标记
      productId: '',
      isEditMode: false,

      form: {
        images: [],
        title: "",
        name: "",
        minYearOld: 3,
        maxYearOld: 18,
        parentsAccompanied: false,
        // 用于二级分类选择的临时变量
        currentMainCategoryIndex: -1
      },
      ageRange: [6, 18],
      isSaving: false,
      isUploading: false,
      hasReadAgreement: false,
      expanded: {
        feature: false,
        itinerary: false,
        included: false,
        excluded: false,
        other: false,
        riskPrompt: false,
        guaranteePrompt: false,
        bookingInfo: true
      },
      // 图片加载错误标记数组
      imageErrors: [],
      // 模拟数据
      productFeatures: [
        {
          type: 'text',
          alt: '探索自然奥秘',
          order: 1
        }
      ]
    };
  },
  computed: {
    // 计算属性：产品特色预览
    featurePreview() {
      if (!this.productStore || !this.productStore.subPageData) return '';

      // 优先使用新的productFeatures数组数据
      if (this.productStore.subPageData?.productFeatures.length > 0) {
        const firstTextItem = this.productStore.subPageData.productFeatures.find(item => item.type === 'text' && item.alt);
        if (firstTextItem) {
          const preview = firstTextItem.alt.replace(/[\n\r]/g, ' ').trim();
          return preview.length > 15 ? preview.substring(0, 15) + '...' : preview;
        }
        // 统计图片数量
        const imageCount = this.productStore.subPageData.productFeatures.filter(item => item.type === 'image' && item.imgUrl).length;
        if (imageCount > 0) {
          return `共${this.productStore.subPageData.productFeatures.length}个特色元素（${imageCount}张图片）`;
        }
        return `共${this.productStore.subPageData.productFeatures.length}个特色元素`;
      }

      // 兼容旧的feature数据
      const content = this.productStore.subPageData.feature;
      if (!content || (typeof content === 'string' && content.trim() === '[]')) return '';

      // 避免显示JSON字符串
      if (typeof content === 'string') {
        try {
          // 尝试解析内容，看看是否是JSON字符串
          const parsedContent = JSON.parse(content);
          if (Array.isArray(parsedContent)) {
            // 如果是数组，返回元素数量
            return `共${parsedContent.length}个特色元素`;
          }
        } catch (e) {
          // 如果不是JSON字符串，直接处理
        }

        // 处理普通字符串，避免显示纯数字
        const preview = content.replace(/[\n\r]/g, ' ').trim();
        // 检查是否是纯数字字符串，如果是则返回更友好的提示
        if (/^\d+$/.test(preview)) {
          return '包含数字类型的产品特色';
        }
        return preview.length > 15 ? preview.substring(0, 15) + '...' : preview;
      } else {
        // 对于非字符串类型，返回更友好的提示
        return '包含产品特色信息';
      }
    },

    // 计算属性：行程摘要数据
    itinerarySummary() {
      if (!this.productStore || !this.productStore.subPageData || !this.productStore.subPageData.specificItinerary || this.productStore.subPageData.specificItinerary.length === 0) {
        return [];
      }

      return this.productStore.subPageData.specificItinerary.map((dayItinerary) => {
        return {
          title: dayItinerary.main || `第${dayItinerary.day}天行程`,
          items: dayItinerary.items || [],
          firstItem: dayItinerary.items && dayItinerary.items.length > 0 ? dayItinerary.items[0].title : ''
        };
      });
    },

    // 计算属性：费用包含预览
    expensesIncludedPreview() {

      console.log("费用包含预览")
      const firstItem = this.productStore.subPageData.expensesIncluded[0];
      return firstItem.title + ': ' + (firstItem.alt.length > 15 ? firstItem.alt.substring(0, 15) + '...' : firstItem.alt);
    },

    // 计算属性：费用不含预览
    expensesExcludedPreview() {

      console.log("费用不含预览")
      const firstItem = this.productStore.subPageData.expensesExcluded[0];
      return firstItem.title + ': ' + (firstItem.alt.length > 15 ? firstItem.alt.substring(0, 15) + '...' : firstItem.alt);
    },

    // 计算属性：风险提示预览
    riskPromptPreview() {

      console.log("风险提示预览")
      const content = this.productStore.subPageData.riskPrompt;
      if (!content) return '';
      const preview = content.replace(/[\n\r]/g, ' ').trim();
      return preview.length > 15 ? preview.substring(0, 15) + '...' : preview;
    },

    // 计算属性：保障提示预览
    guaranteePromptPreview() {
      const content = this.productStore.subPageData.guaranteePrompt;
      if (!content) return '';
      const preview = content.replace(/[\n\r]/g, ' ').trim();
      return preview.length > 15 ? preview.substring(0, 15) + '...' : preview;
    },

    // 计算属性：经营协议预览
    bookingInfoPreview() {

      const content = this.productStore.subPageData.bookingInfo;
      if (!content) return '';
      const preview = content.replace(/[\n\r]/g, ' ').trim();
      return preview.length > 15 ? preview.substring(0, 15) + '...' : preview;
    },

    // 表单是否有效
    isFormValid() {
      const hasTitle = this.form.title && this.form.title.trim().length >= 2;
      const hasCategory = !!this.form.title;
      const hasImage = this.form.images && this.form.images.length > 0;
      return hasTitle && hasCategory && hasImage;
    },

    // 计算属性：当前选中的一级分类文本
    selectedMainCategory() {
      return this.form.title.split(' - ')[0] || '';
    },

    // 计算属性：当前选中的二级分类文本
    selectedSubCategory() {
      return this.form.title.split(' - ')[1] || '';
    },

    // 计算属性：当前选中的一级分类下的二级分类列表
    // 当一级分类未选择时，返回所有可用的二级分类
    currentSubCategories() {
      // 如果一级分类已选择，返回对应分类下的子分类
      if (this.selectedMainCategory) {
        const mainCategory = this.categoryOptions.find(cat => cat.text === this.selectedMainCategory);
        return mainCategory ? mainCategory.child : [];
      }

      // 如果一级分类未选择，返回所有分类的子分类（合并后去重）
      let allSubCategories = [];
      this.categoryOptions.forEach(title => {
        if (title.child && title.child.length > 0) {
          allSubCategories = [...allSubCategories, ...title.child];
        }
      });

      return allSubCategories;
    }
  },
  watch: {
    ageRange: {
      handler(newRange) {
        // 同步更新form中的minYearOld和maxYearOld
        this.form.minYearOld = newRange[0];
        this.form.maxYearOld = newRange[1];
      },
      deep: true
    }
  },
  onLoad(options) {
    console.log('options:', options);
    this.companyInfo = uni.getStorageSync('companyInfo')
    console.log('companyInfo:', this.companyInfo);
    this.productId = options.id;
    if (options.mode != null || '') {
      this.isEditMode = true;
    }
    console.log('this.productId:', this.productId);
    console.log('this.isEditMode:', this.isEditMode);

    this.productStore = useProductStore();
    // 如果是编辑模式，从API加载数据
    if (this.isEditMode && this.productId != null) {
      // 获取产品详情并加载到store
      this.loadProductDetail(this.productId);
    }
    // 初始化监听表单变化，设置自动保存
    this.initFormWatcher();
  },
  methods: {
    // 初始化表单监听器
    initFormWatcher() {
      // 使用setInterval模拟深度监听
      this.formWatcherInterval = setInterval(() => {
        if (this.productStore && typeof this.productStore.scheduleAutoSave === 'function') {
          this.productStore.scheduleAutoSave();
        }
      }, 2000); // 每2秒检查一次
    },
    beforeUnmount() {
      // 清除表单监听器定时器
      if (this.formWatcherInterval) {
        clearInterval(this.formWatcherInterval);
        this.formWatcherInterval = null;
      }
    },

    onShow() {
      // 初始化产品特色数据 - 使用模拟数据
      try {
        if (this.productStore && !this.productStore.subPageData.productFeatures) {
          this.productStore.updateSubPageData('productFeatures', this.productFeatures);
          console.log('初始化产品特色模拟数据');
        }
      } catch (e) {
        console.error('初始化产品特色数据失败:', e);
      }

      // 强制刷新页面数据（防止数据更新但视图不更新的问题）
      this.$forceUpdate();
    },
    // 导航到协议页面
    goAgreement() {
      this.saveCurrentState();
      // 所有数据都通过productStore管理，无需额外保存到本地存储
      // uni.navigateTo({ 
      //   url: '/pages/merchant/create/rules' 
      // });
    },

    // 显示协议弹窗
    showAgreement(agreement) {
      this.currentAgreement = agreement;
      this.popupTitle = agreement;
      this.showPopup = true;
    },

    // 关闭协议弹窗
    closeAgreementPopup() {
      this.showPopup = false;
    },

    // 弹窗关闭回调
    onPopupClose() {
      this.showPopup = false;
    },

    // 处理已阅读协议单选框变化
    handleReadChange(value) {
      this.hasReadAgreement = value;
    },
    //编辑模式加载详情
    async loadProductDetail(productId) {

      try {
        //获取商家类型
        const merchantType = this.companyInfo.businessType;
        //获取产品信息
        const res = await request({
          url: `/product-spu/getProduct?id=${productId}&merchantType=${merchantType}`,
          method: 'GET'
        });
        console.log(res);

        this.form.images = [...res.data.p2.productSku.images]
        this.form.title = res.data.p2.productSku.title
        this.form.name = res.data.p2.productSpu.name
        this.form.minYearOld = res.data.p2.productSku.minYearOld;
        this.form.maxYearOld = res.data.p2.productSku.maxYearOld;
        this.form.parentsAccompanied = res.data.p2.productSku.parentsAccompanied;
        // 确保数组存在再执行push操作
        if (Array.isArray(res.data.p2.productSku.customizationPrompt)) {
          this.productStore.subPageData.customizationPrompt = [...res.data.p2.productSku.customizationPrompt];
        }

        if (Array.isArray(res.data.p2.productSku.productFeatures)) {
          this.productStore.subPageData.productFeatures = [...res.data.p2.productSku.productFeatures];
        }

        if (Array.isArray(res.data.p2.productSku.specificItinerary)) {
          this.productStore.subPageData.specificItinerary = [...res.data.p2.productSku.specificItinerary];
        }

        if (Array.isArray(res.data.p2.productSku.expensesIncluded)) {
          this.productStore.subPageData.expensesIncluded = [...res.data.p2.productSku.expensesIncluded];
        }

        if (Array.isArray(res.data.p2.productSku.expensesExcluded)) {
          this.productStore.subPageData.expensesExcluded = [...res.data.p2.productSku.expensesExcluded];
        }

        if (Array.isArray(res.data.p2.productSku.otherExpenses)) {
          this.productStore.subPageData.otherExpenses = [...res.data.p2.productSku.otherExpenses];
        }

        this.productStore.subPageData.guaranteePrompt = res.data.p2.productSku.guaranteePrompt;
        this.productStore.subPageData.riskPrompt = res.data.p2.productSku.riskPrompt;

      } catch (error) {
        console.error('加载产品详情失败:', error);
        uni.showToast({ title: '加载产品详情失败', icon: 'none' });
      }
    },

    // 保存当前页面状态到store
    saveCurrentState() {
      try {
        // 保存主表单数据到store
        this.productStore.updateMainForm({
          title: this.form.title,
          category: this.form.title,
          images: this.form.images,
          tags: this.form.tags || [],
          ageRange: [this.form.minYearOld, this.form.maxYearOld],
          needParent: this.form.parentsAccompanied,
          businessType: this.form.businessType || 0,
          channelType: this.form.channelType || '',
          campAttribute: this.form.campAttribute || ''
        });

        // 保存子页面数据到store
        // 费用数据已经通过各编辑页面直接保存到store，这里无需重复保存
      } catch (e) {
        console.error('保存当前页面状态失败:', e);
      }
    },

    goBack() {
      this.productId = null;
      this.isEditMode = false;
      uni.navigateBack();
    },

    async chooseImage() {
      if (this.isUploading) return;
      const remain = 8 - this.form.images.length;
      if (remain <= 0) return;

      this.isUploading = true;
      uni.showLoading({ title: '正在选择图片...' });

      try {
        const res = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: remain,
            sizeType: ['compressed', 'original'],
            success: resolve,
            fail: reject,
          });
        });

        const tempFiles = res.tempFiles || [];
        const maxSingleSize = 5 * 1024 * 1024; // 5MB
        const needCompressThreshold = 600 * 1024; // 600KB

        uni.hideLoading();
        uni.showLoading({ title: `正在上传 0/${tempFiles.length}` });

        const results = [];
        let uploadedCount = 0;

        for (let i = 0; i < tempFiles.length; i++) {
          const file = tempFiles[i];
          if (file.size > maxSingleSize) {
            uni.showToast({ title: '部分图片超过5MB已跳过', icon: 'none' });
            continue;
          }

          let path = file.path || (res.tempFilePaths ? res.tempFilePaths[i] : '');
          if (!path) continue;

          // 如果图片较大，先压缩
          if (file.size > needCompressThreshold) {
            try {
              const compressed = await new Promise((resolve, reject) => {
                uni.compressImage({
                  src: path,
                  quality: 70,
                  success: resolve,
                  fail: reject,
                });
              });
              path = compressed.tempFilePath || path;
            } catch (e) {
              console.error('压缩图片失败:', e);
              // 压缩失败则使用原图
            }
          }

          // 上传图片到服务器
          try {
            const uploadRes = await this.uploadImageToServer(path);
            uploadedCount++;
            uni.showLoading({ title: `正在上传 ${uploadedCount}/${tempFiles.length}` });

            // 创建符合数据库结构的图片对象，使用服务器返回的URL
            results.push({
              url: uploadRes.url,
              alt: "",
              order: this.form.images.length + results.length,
              width: uploadRes.width || 0,
              height: uploadRes.height || 0
            });
          } catch (uploadErr) {
            console.error('上传图片失败:', uploadErr);
            uni.showToast({
              title: '部分图片上传失败',
              icon: 'none',
              duration: 2000
            });
          }
        }

        if (results.length) {
          // 合并并保持最多8张图片
          this.form.images = this.form.images.concat(results).slice(0, 8);
          // 重新计算order属性，确保连续不重复
          this.form.images.forEach((img, index) => {
            img.order = index;
          });

          uni.showToast({
            title: `成功上传${results.length}张图片`,
            icon: 'success'
          });
        }
      } catch (err) {
        console.error('选择图片失败:', err);
        // ignore cancel
      } finally {
        uni.hideLoading();
        this.isUploading = false;
      }
    },

    /**
     * 上传图片到服务器
     * @param {String} filePath 本地临时文件路径
     * @returns {Promise<Object>} 返回服务器URL等信息
     */
    uploadImageToServer(filePath) {
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('accessToken') || '';

        uni.uploadFile({
          url: `https://abc.qctrips.cn/local-file/upload`,
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': token
          },
          success: (uploadRes) => {
            if (uploadRes.statusCode === 200) {
              try {
                const data = JSON.parse(uploadRes.data);
                if (data.code === 200 && data.data) {
                  resolve({
                    url: data.data.url || data.data.objectUrl,
                    width: 0,
                    height: 0
                  });
                } else {
                  reject(new Error(data.msg || '上传失败'));
                }
              } catch (e) {
                reject(new Error('解析服务器响应失败'));
              }
            } else {
              reject(new Error(`上传失败，状态码：${uploadRes.statusCode}`));
            }
          },
          fail: (err) => {
            console.error('上传请求失败:', err);
            reject(err);
          }
        });
      });
    },

    confirmRemove(index) {
      uni.showModal({
        title: "提示",
        content: "确定删除这张图片吗？",
        success: (res) => {
          if (res.confirm) {
            this.form.images.splice(index, 1);
            // 重新计算剩余图片的order属性，确保连续不重复
            this.form.images.forEach((img, idx) => {
              img.order = idx;
            });
          }
        },
      });
    },

    // 一级类别选择变化
    onMainCategoryChange(e) {
      const mainCategoryIndex = e.detail.value;
      const mainCategory = this.categoryOptions[mainCategoryIndex];

      // 重置二级分类选择
      this.form.title = mainCategory.text;

      // 如果一级分类有子分类，自动选择第一个子分类
      if (mainCategory.child && mainCategory.child.length > 0) {
        this.form.title = `${mainCategory.text} - ${mainCategory.child[0].text}`;
      }
    },

    // 二级类别选择变化
    onSubCategoryChange(e) {
      const subCategoryIndex = e.detail.value;
      const subCategory = this.currentSubCategories[subCategoryIndex];

      // 更新完整分类信息
      this.form.title = `${this.selectedMainCategory} - ${subCategory.text}`;
    },

    // 跳转到产品特色页面
    goToFeature() {
      this.saveCurrentState();
      uni.navigateTo({
        url: '/public/create/feature'
      });
    },

    // 图片加载失败处理
    onImageError(event, index) {
      console.error('图片加载失败:', event, '索引:', index);
      // 设置错误标记
      if (!this.imageErrors) {
        this.imageErrors = [];
      }
      this.$set(this.imageErrors, index, true);
      // 尝试使用占位图替换
      // event.target.src = '/static/images/placeholder.png';
    },

    // 图片加载成功处理
    onImageLoad() {
      // 清除错误标记
      // 可以在这里添加加载成功的逻辑
    },

    // 跳转到行程页面
    goToItinerary() {
      this.saveCurrentState();
      uni.navigateTo({
        url: '/public/create/itinerary'
      })
    },

    // 跳转到费用页面
    goToExpenses(type) {
      this.saveCurrentState();
      uni.navigateTo({
        url: `/public/create/expenses?type=${type}`
      });
    },

    toggleSection(key) {
      this.expanded[key] = !this.expanded[key];
    },

    onPreview() {
      if (!this.isFormValid) {
        uni.showToast({ title: '请填写必要信息', icon: 'none' });
        return;
      }
      // 实现预览功能
      uni.showToast({ title: '预览功能开发中', icon: 'none' });
    },
    //保存编辑产品
    async onUpdate() {
      if (!this.isFormValid || !this.hasReadAgreement || this.isSaving || this.isUploading)
        return;
      this.isSaving = true;
      try {
        const companyInfo = uni.getStorageSync("companyInfo")
        if (!companyInfo) {
          uni.showToast({ title: '请先完善商家信息', icon: 'none' });
          return;
        }
        const spuId = this.productId;
        //准备数据
        const data = this.prepareSubmitData();
        const res = await request({
          url: `/product-spu/update?spuId=${spuId}`,
          method: 'PUT',
          data: data
        });
        if (res.code == 200) {
          uni.showToast({
            title: '产品保存成功', icon: 'success'
          })
          setTimeout(() => {
            //重置表单
            this.form = {}
            this.productStore.resetForm()
            uni.navigateBack();
          }, 500);
        }
      } catch (error) {
        console.error('保存产品失败:', error);
        uni.showToast({ title: '保存失败，请重试', icon: 'none' });
      } finally {
        this.isSaving = false;
        this.productId = null;
        this.isEditMode = false;
      }
    },

    // 提交创建产品
    async onNext() {
      if (!this.isFormValid || !this.hasReadAgreement || this.isSaving || this.isUploading)
        return;

      this.isSaving = true;
      try {
        const companyInfo = uni.getStorageSync("companyInfo")
        if (!companyInfo) {
          uni.showToast({ title: '请先完善商家信息', icon: 'none' });
          return;
        }

        //准备数据
        const data = this.prepareSubmitData();
        const res = await request({
          url: '/product-spu/create',
          method: 'POST',
          data: data
        });

        if (res.code === 200) {
          uni.showToast({ title: '产品创建成功', icon: 'success' });
          // this.form = {}
          // this.productStore.resetForm()
          // 跳转到产品详情页或其他页面
          //延迟0.5s再跳转 到创建班期页
          const id = res.data;
          console.log('id', id);
          setTimeout(() => {
            uni.navigateTo({ url: `/public/period/periodCreate?id=${id}` });
          }, 500);
        } else {
          uni.showToast({ title: res.message || '创建失败', icon: 'none' });
        }
      } catch (error) {
        console.error('创建产品失败:', error);
        uni.showToast({ title: '请补全数据', icon: 'none' });
      } finally {
        this.isSaving = false;
      }
    },

    // 准备提交/编辑数据
    prepareSubmitData() {
      const companyInfo = uni.getStorageSync("companyInfo")

      // 准备图片数据
      const images = this.form.images.map((img, index) => ({
        url: img.url,
        alt: img.alt || '',
        order: img.order || index + 1,
        width: img.width || 0,
        height: img.height || 0
      }));

      // 准备费用包含数据
      const expensesIncludeds = [];
      if (this.productStore.subPageData.expensesIncluded.length > 0) {
        expensesIncludeds.push(...this.productStore.subPageData.expensesIncluded);
      }
      //准备不含数据
      const expensesExcludeds = [];
      if (this.productStore.subPageData.expensesExcluded.length > 0) {
        expensesExcludeds.push(...this.productStore.subPageData.expensesExcluded);
      }
      // 准备其他费用数据
      const otherExpenses = [];
      if (this.productStore.subPageData.otherExpenses.length > 0) {
        otherExpenses.push(...this.productStore.subPageData.otherExpenses);
      }

      // 准备产品特色数据 - 使用新的productFeatures数组
      let productFeatures = [];
      if (this.productStore.subPageData.productFeatures.length > 0) {
        productFeatures = [...this.productStore.subPageData.productFeatures];
      } else {
        // 如果没有产品特色数据，使用模拟数据作为默认值
        productFeatures = this.productFeatures;
      }
      console.log("this.itinerarySummary()", this.itinerarySummary)
      // 准备行程数据
      const specificItinerarys = [];
      if (this.productStore && this.productStore.subPageData && this.productStore.subPageData.specificItinerary && Array.isArray(this.productStore.subPageData.specificItinerary)) {
        this.productStore.subPageData.specificItinerary.forEach((day, index) => {
          // 处理行程项目中的时间字段，确保格式正确
          const items = (day.items || []).map(item => {
            const processedItem = { ...item };
            // 如果有时间字段且格式不对，进行处理
            if (processedItem.startTime && !processedItem.startTime.includes(':')) {
              delete processedItem.startTime;
            }
            if (processedItem.endTime && !processedItem.endTime.includes(':')) {
              delete processedItem.endTime;
            }
            return processedItem;
          });

          specificItinerarys.push({
            day: day.day || index + 1,
            main: day.main || day.title || '',
            items: items
          });
        });
      }

      // 获取风险提示和保障提示数据
      const riskPrompt = this.productStore && this.productStore.subPageData ? this.productStore.subPageData.riskPrompt || '' : '';
      const guaranteePrompt = this.productStore && this.productStore.subPageData ? this.productStore.subPageData.guaranteePrompt || '' : '';


      return {
        "businessType": companyInfo.businessType,
        "productSpu": {
          "merchantId": companyInfo.id,
          "name": this.form.name,
          "mainImage": this.form.images[0].url || '',
          "originType": 0,
          "originalSpuId": 0,
          "status": 1 // 1表示待审核
        },
        "productSku": {
          "merchantId": companyInfo.id,
          "title": this.form.title,
          "images": images,
          "productFeatures": productFeatures,
          "expensesIncluded": expensesIncludeds,
          "otherExpenses": otherExpenses,
          "expensesExcluded": expensesExcludeds,
          "minYearOld": this.form.minYearOld,
          "maxYearOld": this.form.maxYearOld,
          "parentsAccompanied": this.form.parentsAccompanied ? 1 : 0,
          "riskPrompt": riskPrompt,
          "guaranteePrompt": guaranteePrompt,
          "specificItinerary": specificItinerarys,
          "customizationPrompt": []
        }
      };

    }
  }
};
</script>

<style lang="scss">
.app-container {
  display: flex;
  flex-direction: column;
}

.content {
  padding: 150rpx 0 150rpx 0;
  flex: 1;
  background: #f5f5f5;
}

.card {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin: 0 20rpx 20rpx 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  font-weight: bold;
  font-size: 30rpx;
  margin-bottom: 12rpx;
}

.card-header.expandable {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.arrow {
  font-size: 24rpx;
  color: #888;
}

.card-body {
  font-size: 26rpx;
  margin-right: 20rpx;
  color: #333;
}

.tips {
  font-size: 24rpx;
  color: #888;
  margin-top: 8rpx;
}

.image-upload {
  display: flex;
  flex-wrap: wrap;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
}

.image-item image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

/* 图片加载失败占位符样式 */
.image-error-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 24rpx;
  border-radius: 8rpx;
  z-index: 1;
}

.delete {
  position: absolute;
  top: 4rpx;
  right: 4rpx;
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  border-radius: 50%;
  padding: 2rpx 8rpx;
  font-size: 24rpx;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #ccc;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48rpx;
  color: #999;
}

.picker-value {
  font-size: 28rpx;
  color: #333;
  padding: 10rpx 0;
}

.input {
  width: 100%;
  padding: 12rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
}

.input-count {
  text-align: right;
  font-size: 22rpx;
  color: #aaa;
  margin-top: 8rpx;
}

.link {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.link-text {
  color: #007aff;
}

.inner-edit-btn {
  size: mini;
  margin-top: 16rpx;
  background: #007aff;
  color: #fff;
  border-radius: 8rpx;
  padding: 16rpx 24rpx;
}

.section-content {
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666;
}

.expense-item {
  margin-bottom: 20rpx;
  padding: 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.expense-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
}

.expense-content {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
}

.form-item {
  margin-bottom: 20rpx;
}

.bottom-btns {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background: #fff;
  border-top: 2rpx solid #eee;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.btn {
  flex: 1;
  margin: 0 10rpx;
  padding: 20rpx 0;
  border-radius: 12rpx;
  font-size: 28rpx;
}

.preview {
  background: #f0f0f0;
  color: #333;
}

.draft {
  background: #ffeeba;
  color: #333;
}

.next {
  background: #007aff;
  color: #fff;
}

.link-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15rpx 0;
  color: #007aff;
}

.content-preview {
  font-size: 24rpx;
  color: #666;
  flex: 1;
  text-align: right;
  margin-left: 20rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-content {
  padding: 8rpx 0;
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
}

/* 行程摘要样式 */
.itinerary-day-summary {
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.itinerary-day-summary:last-child {
  border-bottom: none;
}

.day-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 10rpx;
}

/* 行程项目容器样式 */
.day-items {
  margin-left: 30rpx;
  margin-top: 10rpx;
}

/* 单个行程项目样式 */
.itinerary-item {
  padding: 10rpx 0;
  margin-bottom: 10rpx;
}

/* 行程项目标题样式 */
.item-title {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}

/* 行程项目类型标签样式 */
.item-type {
  padding: 4rpx 12rpx;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 16rpx;
  font-size: 22rpx;
  margin-right: 10rpx;
}

/* 行程项目名称样式 */
.item-name {
  font-size: 26rpx;
  color: #333;
}

/* 行程项目详情样式 */
.item-details {
  margin-left: 60rpx;
  font-size: 24rpx;
  color: #666;
}

/* 行程时间样式 */
.item-time {
  display: block;
  margin-bottom: 4rpx;
}

/* 行程地点样式 */
.item-address {
  display: block;
}

/* 空行程提示样式 */
.empty-items {
  margin-left: 30rpx;
  color: #999;
  font-size: 24rpx;
  padding: 20rpx 0;
}

.day-items-summary {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  font-size: 24rpx;
  color: #666;
}

.items-count {
  margin-right: 16rpx;
}

.first-item {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.day-desc {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
  line-height: 1.5;
}

/* 分类容器样式 - 用于将一级和二级分类放在同一行 */
.category-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

/* 每个分类项的样式 */
.category-item {
  flex: 1;
}

/* 移除二级分类的上边距 */
.sub-category-picker {
  margin-top: 0;
}

/* 确保两个选择器样式一致 */
.picker-value {
  padding: 20rpx;
  background-color: #f8f8f8;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  text-align: center;
}

/* 年龄范围滑块样式 */
.age-range-slider {
  margin: 20rpx 0;
}

/* up-slider组件样式 */
:deep(.u-slider) {
  margin: 20rpx 0;
}

:deep(.u-slider__track) {
  height: 6rpx;
  background-color: #e0e0e0;
}

:deep(.u-slider__fill) {
  height: 6rpx;
  background-color: #007aff;
}

:deep(.u-slider__button) {
  width: 32rpx;
  height: 32rpx;
  border-radius: 50%;
  background-color: #fff;
  border: 2rpx solid #007aff;
  box-shadow: 0 2rpx 8rpx rgba(0, 122, 255, 0.3);
}

:deep(.u-slider__value) {
  position: absolute;
  top: -40rpx;
  font-size: 24rpx;
  color: #666;
  background-color: #fff;
  padding: 4rpx 12rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 提示文本样式 */
.tips {
  display: block;
  text-align: center;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #666;
}

/* 协议链接样式 */
.agreement-links {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  padding: 16rpx 0;
}

.agreement-link {
  color: #007aff;
  font-size: 28rpx;
}

.agreement-divider {
  margin: 0 8rpx;
  color: #999;
  font-size: 28rpx;
}

/* 已阅读协议单选框样式 */
.agreement-read {
  margin-top: 20rpx;
}

.radio-group {
  display: flex;
  align-items: center;
}

.radio {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

/* 弹窗样式 */
.popup-container {
  background: #fff;
  border-radius: 16rpx 16rpx 0 0;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  border-bottom: 2rpx solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  height: 500rpx;
  padding: 24rpx;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;
}

.agreement-content {
  font-size: 28rpx;
  line-height: 1.6;
  word-wrap: break-word;
  word-break: break-all;
}

.agreement-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 16rpx;
}

.agreement-date {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 24rpx;
}

.agreement-paragraph {
  display: block;
  margin-bottom: 20rpx;
  color: #333;
  white-space: pre-wrap;
}

.popup-footer {
  padding: 24rpx;
  border-top: 2rpx solid #eee;
}

.popup-btn {
  width: 100%;
  background: #007aff;
  color: #fff;
  border-radius: 8rpx;
  padding: 20rpx 0;
  font-size: 28rpx;
}
</style>
